<script setup>
import { dict, useTypes, compute } from '@fast-crud/fast-crud'
import http from '@/http'
import { merge } from 'lodash-es'
import Step1 from './components/step-1.vue'
import Step2 from './components/step-2.vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { Modal } from 'ant-design-vue'
import { createVNode } from 'vue'

const currentStep = ref(0)

const router = useRouter()
const crudTypes = useTypes()
const formRef = ref(null)
const projectDict = dict({
  label: 'name',
  value: 'id',
  data: []
})
provide('projectDict', projectDict)
const getProjectDict = async (form) => {
  const res = await http.post('/project/find_huawei_cloud', {
    domain: form.domain,
    ak: form.ak,
    sk: form.sk
  })
  if (Array.isArray(res)) {
    projectDict.setData(res)
  }
}
const checkForm = (form) => Boolean(form.domain) && Boolean(form.ak) && Boolean(form.sk)
const formOptions = ref({
  col: {
    span: 12
  },
  row: {
    gutter: 20
  },
  labelCol: {
    span: 8
  },
  labelAlign: 'left',
  columns: {
    region: {
      title: '产品',
      component: merge({}, crudTypes.getType('dict-select').form.component, {
        dict: dict({
          async getData() {
            const res = await http.post('/product/find')
            return (res || []).map((el) => ({
              label: el,
              value: el
            }))
          }
        })
      }),
      rules: [
        {
          required: true,
          message: '请选择'
        }
      ]
    },
    domain: {
      title: '账户/租户ID',
      component: merge({}, crudTypes.getType('text').form.component, {}),
      rules: [
        {
          required: true,
          message: '请输入'
        }
      ]
    },
    ak: {
      title: 'ak',
      component: merge({}, crudTypes.getType('text').form.component, {}),
      rules: [
        {
          required: true,
          message: '请输入'
        }
      ]
    },
    sk: {
      title: 'sk',
      component: merge({}, crudTypes.getType('text').form.component, {}),
      rules: [
        {
          required: true,
          message: '请输入'
        }
      ]
    },
    projectID: {
      title: '项目',
      component: merge({}, crudTypes.getType('dict-select').form.component, {
        disabled: compute(({ form }) => !checkForm(form)),
        dict: projectDict
      }),
      rules: [
        {
          required: true,
          message: '请选择'
        }
      ]
    }
  },
  onValueChange(context) {
    const { form, key } = context || {}
    if (checkForm(form) && key !== 'projectID') {
      getProjectDict(form)
    }
  }
})
const setp1Ref = ref(null)
const baseFormData = computed(() => unref(formRef)?.getFormData?.() || {})
const nextAction = async () => {
  if (unref(currentStep) === 0) {
    unref(formRef)
      .getFormRef()
      .validate()
      .then(() => {
        currentStep.value = 1
      })
  } else if (unref(currentStep) === 1) {
    await unref(setp1Ref).doSubmit?.()
    currentStep.value = 2
  }
}
const step2FormData = computed(() => {
  const projectName = projectDict.getNodeByValue(unref(baseFormData).projectID)?.name || ''
  return {
    ...unref(baseFormData),
    region: projectName,
    productType: unref(baseFormData).region,
    vpc: unref(setp1Ref).formData?.vpc,
    parameter: JSON.stringify({
      project: unref(baseFormData).projectID,
      projectName,
      productType: unref(baseFormData).region,
      ...unref(setp1Ref).formData
    })
  }
})

const submitAction = async () => {
  Modal.confirm({
    title: '警告',
    icon: createVNode(ExclamationCircleOutlined),
    content: '该实例一旦创建无法撤销，是否继续？',
    async onOk() {
      const res = await http.post('/guanplus/create', step2FormData.value, {
        unpack: true
      })
      if (res.code === 1) {
        Modal.success({
          title: '创建成功',
          content: '请前往任务列表页查看',
          onOk() {
            return router.push({
              name: '/'
            })
          }
        })
      }
    },
    onCancel() {}
  })
}
</script>

<template>
  <div class="w-10/12 mx-auto py-4">
    <a-breadcrumb>
      <a-breadcrumb-item>
        <router-link to="/">列表</router-link>
      </a-breadcrumb-item>
      <a-breadcrumb-item>创建</a-breadcrumb-item>
    </a-breadcrumb>
    <div class="bg-white p-4 my-4">
      <a-steps
        :current="currentStep"
        :items="[
          {
            title: '基本信息'
          },
          {
            title: '高级参数'
          },
          {
            title: '确认'
          }
        ]"
      ></a-steps>
    </div>
    <div class="bg-white p-4 mb-4">
      <fs-form ref="formRef" v-bind="formOptions" v-show="currentStep === 0" />
      <div v-show="currentStep === 1">
        <a-descriptions>
          <a-descriptions-item label="项目">
            <fs-values-format
              :model-value="baseFormData.projectID"
              :dict="projectDict"
              type="text"
            />
          </a-descriptions-item>
          <a-descriptions-item label="AK">
            {{ baseFormData.ak }}
          </a-descriptions-item>
          <a-descriptions-item label="SK">
            {{ baseFormData.sk }}
          </a-descriptions-item>
        </a-descriptions>

        <step1
          ref="setp1Ref"
          v-if="baseFormData.projectID"
          :baseFormData="baseFormData"
          :projectDict="projectDict"
          :key="baseFormData.projectID"
        />
      </div>
      <div v-if="currentStep === 2">
        <step2 :form-data="step2FormData" :projectDict="projectDict" />
      </div>
    </div>
    <div class="bg-white p-4 mb-4 text-right">
      <a-space>
        <a-button v-if="currentStep > 0" @click="currentStep--">上一步</a-button>
        <a-button v-if="currentStep < 2" type="primary" @click="nextAction">下一步</a-button>
        <a-button v-else type="primary" @click="submitAction">提交</a-button>
      </a-space>
    </div>
  </div>
</template>

<style scoped lang="less"></style>
